/* Copyright 2008. All rights reserved. */
package org.bling.swt.widgets;

import org.bling.swt.BlingLayoutData;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.PaintEvent;
import org.eclipse.swt.events.PaintListener;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Canvas;
import org.eclipse.swt.widgets.Composite;

public class ImageCanvas extends Canvas implements PaintListener {

	private Image image;

	public ImageCanvas(Composite parent, Image image) {
		super(parent, SWT.SHELL_TRIM | SWT.NO_BACKGROUND | SWT.NO_REDRAW_RESIZE);
		this.image = image;
		addPaintListener(this);
		
		if (image != null) {
			// Assist the Bling Layout in knowing how large this canvas is
			setSize(image.getImageData().width, image.getImageData().height);
			BlingLayoutData data = new BlingLayoutData();
			data.width = image.getImageData().width;
			data.height = image.getImageData().height;
			setLayoutData(data);
		}
	}

	public void paintControl(PaintEvent event) {
		GC gc = event.gc;
		if (image != null) {
		  gc.drawImage(image, 0, 0);
		}
		
		// FIXME: Do something here, if image is null - e.g. broken link image
	}

	public Image getImage() {
		return image;
	}
	
//	TODO: Leverage a function such as this in order to provide custom image sizing on the tag:
//	private Image resize(Image image, int width, int height) {
//		Image scaled = new Image(Display.getDefault(), width, height);
//		GC gc = new GC(scaled);
//		gc.setAntialias(SWT.ON);
//		gc.setInterpolation(SWT.HIGH);
//		gc.drawImage(image, 0, 0,
//		image.getBounds().width, image.getBounds().height,
//		0, 0, width, height);
//		gc.dispose();
//		image.dispose(); // don't forget about me!
//		return scaled;
//	}
}
